
// 当请求以 /data 开头就转发到 http://127.0.0.1:4000/api/xxx
const http = require('http')
module.exports = (req, res, next) => {
    const context = "/data"
    if (!req.path.startsWith(context)) { // 不需要代理
        return next()
    }
    // 需要代码
    const path = req.path.substr(context.length)
    console.log('proxy:', path)
    // 创建代理请求对象
    const request = http.request({
        host: "127.0.0.1",
        port: 4000,
        path,
        method: req.method,
        headers: req.headers
    }, response => {
        //设置响应信息
        res.status(response.statusCode)
        for (const key in response.headers) {
            res.setHeader(key, response.headers[key])
        }
        response.pipe(res)
    })
    // 把请求体写入到代理请求对象的请求体中
    req.pipe(request)
}